<?php
session_start();
class Login extends CI_Controller {
	
	public function __construct(){
		parent::__construct();
		$this->load->model('login_model', '', true);
	}
	
	function index($error_code=0) {
		$login = isset($_SESSION['login'])?$_SESSION['login']:'';
		if(empty($login) || $error_code == 1)
			$this->load->view('login_form');
		else
			redirect('admin/landing');
	}
	
	private function _fill_session($id, $user, $actor, $person_id=''){
		$_SESSION['id'] = $id;
		$_SESSION['user'] = $user;
		$_SESSION['actor'] = $actor;
		$_SESSION['person_id'] = isset($person_id)?$person_id:'none';
	}
	
	function process_login()
	{
		$this->form_validation->set_rules('username', 'Username', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required');
		
		if ($this->form_validation->run() == TRUE) {
			$username = $this->input->post('username');
			$password = $this->input->post('password');

			$rs = $this->login_model->check_user($username, $password);
			
			if(count($rs)>0){
				if($rs->name!="admin"){ 
					$person_id = $this->login_model->get_person_id($rs->id, $rs->name . 's');
					$this->_fill_session($rs->id, $rs->username, $rs->name, $person_id->id);
				}
				else
					$this->_fill_session($rs->id, $rs->username, $rs->name);
				//echo var_dump($person_id);
				
				if($rs->name=="admin"){ 
					redirect('admin/landing');
				}
				else if($rs->name=="teacher"){ 
					redirect('teacher/landing');
				}
				else if($rs->name=="student"){ 
					redirect('student/landing');
				}
			}
			else {
				$this->session->set_flashdata('message', 'Maaf, username dan atau password Anda salah');
				redirect('login');
			}
		}
		else
			$this->load->view('login_form');
	}
	
	function process_logout()
	{
		$_SESSION['id'] = '';
		$_SESSION['user'] = '';
		$_SESSION['actor'] = '';
		$_SESSION['person_id'] = '';
		$_SESSION['subject_id'] = '';
		$_SESSION['subject_name'] = '';
		session_destroy();
		redirect('login', 'refresh');
	}
}
